package com.app.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.app.filter.OAuthInfo;
import com.app.model.Menu;
import com.app.model.RoleUser;
import com.app.model.User;
import com.app.resp.MenuResponse;



@Service
public class OAuthService {
	@Resource
	private UserService userService;
	@Resource
	private MenuService menuService;
	@Resource
	private RoleMenuService roleMenuService;

	public OAuthInfo genOAuthInfo(){
		OAuthInfo info = new OAuthInfo();
		Subject subject  = SecurityUtils.getSubject();
		Serializable sessionId = subject.getSession(true).getId();
		info.setSessionId(String.valueOf(sessionId));
		//用户基本信息
		String loginName = (String) subject.getPrincipal();
		if(StringUtils.isEmpty(loginName)){
			return info;
		}
		User user=userService.getByName(loginName);
		RoleUser roleUser = userService.getRole(user.getId());
		BeanUtils.copyProperties(user, info);
		info.setRoleUser(roleUser);
		List<MenuResponse> list = new ArrayList<MenuResponse>();
		List<Long> ids = roleMenuService.getMenuIdList(roleUser.getId());
		List<Long> subIds = new ArrayList<Long>();
		for(Long id:ids){
			Menu m = menuService.getById(id);
			if(m.getpId() != null){
				subIds.add(id);
			}
		}
		List<Long> parentIds = new ArrayList<Long>();
		for(Long id:ids){
			Menu m = menuService.getById(id);
			if(m.getpId() == null){
				parentIds.add(id);
			}
		}
		for(Long pid:parentIds){
			Menu m = menuService.getById(pid);
			MenuResponse response = new MenuResponse();
			response.setId(m.getId());
			response.setName(m.getName());
			List<Menu> sub = menuService.getSubMenu(m.getId());
			Iterator<Menu> it = sub.iterator();  
		    while(it.hasNext()){
		    	Menu item = (Menu)it.next();
		    	if(!subIds.contains(item.getId())){
		    		it.remove();
				}
		    }
			/*for(Menu item:sub){
				if(!subIds.contains(item.getId())){
					sub.remove(item);
				}
			}*/
			response.setSub(sub);
			list.add(response);
		}
		
		info.setList(list);
		return info;
		
	}
}
